package pl.vanta.mjuzik2.impl.playlists;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.OrFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;

import pl.vanta.mjuzik2.api.PlaylistType;
import pl.vanta.mjuzik2.api.services.PlaylistService;
import pl.vanta.utils.commons.FileUtils;
import pl.vanta.utils.gui.filters.GuiFileFilter;
import pl.vanta.utils.gui.filters.SaveFileFilter;

import com.google.inject.Inject;

public class PlaylistServiceImpl implements PlaylistService
{
	private final List<PlaylistType>	playlistTypes;

	@Inject
	public PlaylistServiceImpl(List<PlaylistType> playlistTypes)
	{
		this.playlistTypes = playlistTypes;
	}

	@Override
	public List<PlaylistType> getPlaylistTypes()
	{
		return this.playlistTypes;
	}

	public List<File> getAllFilesFromPlaylists(File[] files)
	{
		List<File> fileList = new ArrayList<File>();

		List<File> playlists = FileUtils.getAllFilesRecursive(files, getPlaylistFilesFilter());

		for (File file : playlists)
		{
			fileList.addAll(loadPlaylist(file));
		}

		return fileList;
	}

	public List<File> loadPlaylist(File playlist)
	{
		List<File> files = new ArrayList<File>();

		for (PlaylistType type : this.playlistTypes)
		{
			List<File> list = type.loadPlaylist(playlist);

			if (list != null)
			{
				files.addAll(list);

				return files;
			}
		}

		return files;
	}

	public List<GuiFileFilter> getPlaylistFilesFilters()
	{
		List<GuiFileFilter> filters = new ArrayList<GuiFileFilter>();

		for (PlaylistType pt : this.playlistTypes)
		{
			SuffixFileFilter sff = new SuffixFileFilter(pt.getExtensions(), IOCase.INSENSITIVE);
			IOFileFilter dff = DirectoryFileFilter.DIRECTORY;

			SaveFileFilter saveff = new SaveFileFilter(new OrFileFilter(sff, dff), pt.getDescription(), pt
					.getExtensions()[0]);
			filters.add(saveff);
		}

		return filters;
	}

	public GuiFileFilter getPlaylistFilesFilter()
	{
		SuffixFileFilter sff = new SuffixFileFilter(getSupportedPlaylistFilesExtensions(), IOCase.INSENSITIVE);
		IOFileFilter dff = DirectoryFileFilter.DIRECTORY;

		GuiFileFilter gff = new GuiFileFilter(new OrFileFilter(sff, dff), "Playlist files");

		return gff;
	}

	public List<String> getSupportedPlaylistFilesExtensions()
	{
		List<String> extensions = new ArrayList<String>();

		for (PlaylistType type : this.playlistTypes)
		{
			extensions.addAll(Arrays.asList(type.getExtensions()));
		}

		return extensions;
	}
}